<script setup lang="ts">
import * as DevicesResponse from "../class/DevicesResponse";
import axios from "axios";
import config from "../assets/config.json";
import {defineAsyncComponent, onMounted, onUpdated, ref} from "vue";
import DeviceSetting from "./DeviceSetting.vue";
import DeviceDetails from "./DeviceDetails.vue";

const DeviceData = defineAsyncComponent(() => import('./DeviceData.vue'));

let deviceName = ref("未知设备");
let onlineStatus = ref("[离线]");
const dashboard = "dashboard";
const settings = "settings";
const details = "details";
let switchTab = ref(dashboard);
let chartView = ref("line");
let chartUpdateDelay = ref(1000*60*3)

const switchTabTo = (target: string) => {
  switchTab.value = target;
};

const currTabIs = (comp: string) => {
  return switchTab.value == comp;
}

const props = defineProps({
  deviceNumber: String,
  dataTag1: String,
  dataTag2: String
});

onMounted(() => {
  updateDevice();
});

function getDevice() : Promise<DevicesResponse.Device> {
  return new Promise<DevicesResponse.Device>((resolve, reject) => {
    axios({
      baseURL: `http://${config.host}:${config.port}`,
      method: "GET",
      url: `${config.apiPrefix}/${config.apiSuffix.getDevices}`,
      params: {
        deviceNumber: props.deviceNumber
      }
    }).then(response => {
      if (response.status == 200 && response.data.status == "success") {
        resolve(response.data.device);
      } else {
        throw Error("status is not success.");
      }
    }).catch(function (error) {
      reject(error);
    });
  });
}

function updateDevice() {
  getDevice().then(device => {
    if (device.name != null) deviceName.value = device.name;
    onlineStatus.value = device.is_online ? "[在线]":"[离线]";
  }).catch((err) => {console.log(err)});
}

</script>
<template>
  <t-layout>
    <t-header>
      <t-head-menu v-model="switchTab" theme="light">
        <h4 style="margin-inline: 20px">{{ deviceName }}{{ onlineStatus }}</h4>
        <t-menu-item :value="dashboard" @click="switchTabTo(dashboard)"> 数据图表 </t-menu-item>
        <t-menu-item :value="settings" @click="switchTabTo(settings)"> 设备设置 </t-menu-item>
        <t-menu-item :value="details" @click="switchTabTo(details)"> 设备详情 </t-menu-item>
      </t-head-menu>
    </t-header>
    <t-content style="background-color: white">
      <DeviceData v-if="currTabIs(dashboard)" :device-number="deviceNumber" :data-tag1="props.dataTag1" :data-tag2="props.dataTag2" :chart-view="chartView" :update-timeout="chartUpdateDelay"/>
      <DeviceSetting
          v-if="currTabIs(settings)"
          :device-number="deviceNumber"
          :chart-view-option="chartView"
          :chart-update-delay="chartUpdateDelay"
          @chartViewOptionChanged="(cv) => chartView = cv"
          @chartUpdateDelayChanged="(delay) => chartUpdateDelay = delay" />
      <DeviceDetails v-if="currTabIs(details)"/>
    </t-content>
  </t-layout>
</template>

<style scoped>

</style>